package ucuserslogic

import (
	"context"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserNotifyMsgListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserNotifyMsgListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserNotifyMsgListLogic {
	return &GetUserNotifyMsgListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 获取消息列表
func (l *GetUserNotifyMsgListLogic) GetUserNotifyMsgList(in *pb.GetUserNotifyMsgListReq) (*pb.GetUserNotifyMsgListResp, error) {
	defer utils.RecoverPanic()

	//
	var err error
	var uns *usercenter.UserNotifyMsgStat
	uns, err = l.svcCtx.UserNotifyMsgStatModel.FindOne(l.ctx, in.Uid)
	if err == sqlx.ErrNotFound {
		return &pb.GetUserNotifyMsgListResp{}, nil
	}
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.GetUserNotifyMsgListResp
	resp.List = make([]*pb.UserNotifyMsg, 0)
	resp.Total = uns.Total
	resp.NotRead = uns.NotRead

	var list []*usercenter.UserNotifyMsg
	list, err = l.svcCtx.UserNotifyMsgModel.Find(l.ctx, in.Uid, in.PageNo, in.PageSize)
	if err == sqlx.ErrNotFound {
		return &resp, nil
	}
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	if len(list) <= 0 {
		return &resp, nil
	}

	for i := 0; i < len(list); i++ {
		vl := pb.UserNotifyMsg{}
		vl.Id = list[i].Id
		vl.MsgType = list[i].MsgType
		vl.MsgContent = list[i].MsgContent
		vl.Title = list[i].Title
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		vl.IsRead = list[i].IsRead
		resp.List = append(resp.List, &vl)
	}

	return &resp, nil
}
